/**
 * 生成日期信息
 */
import { computed, ref } from 'vue'
import { CalendarMode } from '../../../types/tn-calendar'
import { subNumber } from '../../../utils'
import { solar2lunar } from './lunarCalendar'

type CalendarData = {
  value: string | number,
  desc: string,
  select: boolean,
  disabled: boolean
}

type CalendarShowData = {
  month: number,
  data: CalendarData[]
}

export default function generateDateInfo() {

  // 星期对应的中文
  const weekdayZh: string[] = ['日','一','二','三','四','五','六']

  // 日期数据

  // range数据
  let startSelect: boolean = false
  let startYear = ref<number>(0)
  let startMonth = ref<number>(0)
  let startDay = ref<number>(0)
  let endYear = ref<number>(0)
  let endMonth = ref<number>(0)
  let endDay = ref<number>(0)

  const startDate = computed<string>(() => {
    return `${startYear.value}/${subNumber(startMonth.value)}/${subNumber(startDay.value)}`
  })
  const endDate = computed<string>(() => {
    return `${endYear.value}/${subNumber(endMonth.value)}/${subNumber(endDay.value)}`
  })

  let year = ref<number>(0)
  let month = ref<number>(0)
  let day = ref<number>(0)

  // 最小/最大日期
  let minYear = ref<number>(0)
  let minMonth = ref<number>(0)
  let minDay = ref<number>(0)
  let maxYear = ref<number>(0)
  let maxMonth = ref<number>(0)
  let maxDay = ref<number>(0)

  // 配置参数
  let selectValue = ref<string | string[]>('')
  let mode: CalendarMode = 'date'
  let showLunar: boolean = true
  let startText: string = ''
  let endText: string = ''

  // 日期数据
  let calendarData = ref<CalendarShowData[]>([])
  // 当前显示的月份
  let currentShowMonth = ref<number>(1)

  // 初始化数据
  const init = (
    _value: string | string[],
    _mode: CalendarMode, 
    _minDate: string, 
    _maxDate: string,
    _showLunar: boolean,
    _startText: string,
    _endText: string
  ) => {
    mode = _mode
    showLunar = _showLunar
    startText = _startText
    endText = _endText

    // 现在时间
    const nowDate = new Date()
    year.value = nowDate.getFullYear()
    month.value = nowDate.getMonth() + 1
    day.value = nowDate.getDate()
    currentShowMonth.value = month.value - 1

    // yyyy-mm-dd为安卓写法，不支持iOS，需要使用"/"分隔，才能二者兼容
    // 设置最小/最大可选日期
    if (_minDate) {
      _minDate = _minDate.replaceAll('-','/')
      const minDate = new Date(_minDate)
      minYear.value = minDate.getFullYear()
      minMonth.value = minDate.getMonth() + 1
      minDay.value = minDate.getDate()
    }
    if (_maxDate) {
      _maxDate = _maxDate.replaceAll('-','/')
      const maxDate = new Date(_maxDate)
      maxYear.value = maxDate.getFullYear()
      maxMonth.value = maxDate.getMonth() + 1
      maxDay.value = maxDate.getDate()
    }

    // 设置默认值
    setDefaultValue(_value)
  }

  // 设置日历的默认值
  const setDefaultValue = (_value: string | string[]) => {
    if (mode === 'date' && typeof _value === 'string' && _value) {
      selectValue.value = _value.replaceAll('-','/')
      // 如果设置了默认值，同时修改对应year、month、day
      const selectDate = new Date(selectValue.value)
      year.value = selectDate.getFullYear()
      month.value = selectDate.getMonth() + 1
      day.value = selectDate.getDate()
      
    }
    if (Array.isArray(_value) && _value.length > 0) {
      if (mode === 'range') {
        if (_value.length !== 2) {
          return console.error('[tn-calendar] 日期默认值设置格式有误')
        }
        startSelect = false
        // 设置startTime/endTime
        const startTime = new Date((_value as string[])[0].replaceAll('-','/'))
        const endTime = new Date((_value as string[])[1].replaceAll('-','/'))
        startYear.value = startTime.getFullYear()
        startMonth.value = startTime.getMonth() + 1
        startDay.value = startTime.getDate()
        endYear.value = endTime.getFullYear()
        endMonth.value = endTime.getMonth() + 1
        endDay.value = endTime.getDate()

        if (startYear.value !== endYear.value) {
          return console.error('[tn-calendar] 日期默认值设置格式有误, 开始和结束年份需要在同一年')
        }
      }
      selectValue.value = _value.map((item) => item.replaceAll('-','/'))
      const selectDate = new Date(selectValue.value[0])
      year.value = selectDate.getFullYear()
      month.value = selectDate.getMonth() + 1
      day.value = selectDate.getDate()
    }

    // 设置当前显示的月份
    if ((minYear.value && minYear.value === year.value) || 
      (maxYear.value && maxYear.value === year.value)) {
        currentShowMonth.value = 0
    } else {
      currentShowMonth.value = month.value - 1
    }

    generateCalendarArr(((year.value > maxYear.value) && (maxYear.value > 0)) ? maxYear.value : year.value)
  }

  // 更新当前显示月份的值
  const updateCurrentShowMonth = (val: number) => {
    month.value = calendarData.value[val].month
    currentShowMonth.value = val
  }

  // 切换年份
  const updateSelectYear = (val: number) => {
    // console.log(val);
    if (minYear.value && val < minYear.value) return
    if (maxYear.value && val > maxYear.value) return

    // 重置选中的月份
    currentShowMonth.value = 0
    year.value = val

    // 重新生成月份数据
    generateCalendarArr(val)
  }

  // 处理日期点击事件
  const updateSelectValue = (dateValue: string | number) => {
    // console.log(dateValue);
    if (!dateValue) return
    day.value = Number(dateValue)

    // 判断是否为disabled
    const disabled = calendarData.value[currentShowMonth.value].data.find((item) => {
      return item.value == dateValue
    })?.disabled
    if (disabled) return

    // 判断是否什么类型的日历
    if (mode === 'date') {
      // 把之前选中的值取消选中
      if (selectValue.value) {
        if (_sameDate(year.value, month.value, Number(dateValue), selectValue.value as string)) return
        const selectDate = new Date(selectValue.value as string)
        _setDateSelectWithDateValue(selectDate.getDate(), false, selectDate.getMonth() + 1)
      }
      _setDateSelectWithDateValue(dateValue, true)
    } else if (mode === 'multi') {
      const index = _sameDateInArray(year.value, month.value, Number(dateValue), selectValue.value as string[])
      if (index !== -1) {
        const currentSelectDate = new Date((selectValue.value as string[])[index])
        _setDateSelectWithDateValue(currentSelectDate.getDate(), false)
      } else {
        _setDateSelectWithDateValue(dateValue, true)
      }
    } else if (mode === 'range') {
      if ((startYear.value === year.value) && 
        (month.value > startMonth.value || 
          (month.value === startMonth.value && Number(dateValue) > startDay.value))  &&
        startSelect
      ) {
        endYear.value = year.value
        endMonth.value = month.value
        endDay.value = Number(dateValue)
        startSelect = !startSelect
      } else {
        startYear.value = year.value
        startMonth.value = month.value
        startDay.value = Number(dateValue)
        endYear.value = 0
        endMonth.value = 0
        endDay.value = 0
        startSelect = true
      }
      // if (startSelect) {
      //   if (month.value < startMonth.value || (month.value === startMonth.value && Number(dateValue) < startDay.value)) {

      //   } else {
          
      //   }
        
      // } else {
      //   startYear.value = year.value
      //   startMonth.value = month.value
      //   startDay.value = Number(dateValue)
      //   endYear.value = 0
      //   endMonth.value = 0
      //   endDay.value = 0
      //   startSelect = !startSelect
      // }

      // 重新生成日期数据
      generateCalendarArr(year.value)
    }

    _updateSelectValue(dateValue)

    // 切换在mode为range状态时的startSelect的值
    if (mode === 'range') {
      
    }
  }

  // 生成对应的日期数据
  const generateCalendarArr = (_year: number) => {
    let _minMonth = 1
    let _maxMonth = 12
    if (minYear.value === year.value && minMonth.value) {
      _minMonth = minMonth.value
      month.value = _minMonth
    }
    if (maxYear.value === year.value && maxMonth.value) {
      _maxMonth = maxMonth.value
      month.value = _maxMonth
    }
    calendarData.value = []
    for (let i = _minMonth; i <= _maxMonth; i++) {

      // 生成对应月份的日期数据
      const dateData: CalendarData[] = _generateMonthData(_year, i)

      calendarData.value.push({
        month: i,
        data: dateData
      })
    }
  }

  // 生成对应月份的数据
  const _generateMonthData = (_year: number, _month: number): CalendarData[] => {
    // 空白天数
    const emptyDayNumber = _getMonthFirstWeekDay(_year, _month)
    // 当前月份的天数
    const monthDayNumber = _getMonthDay(_year, _month)

    // 建立数据
    let data: CalendarData[] = []
    // 填充空白天数
    // console.log(emptyDayNumber);
    if (emptyDayNumber > 0) {
      data = Array(emptyDayNumber).fill({
        value: '',
        desc: '',
        select: false,
        disabled: true
      })
    }
    // 填充月份数据
    for (let i = 1; i <= monthDayNumber; i++) {
      let desc: string = ''
      let select: boolean = false
      let disabled: boolean = false

      if (showLunar) {
        let value = solar2lunar(_year, _month, i)
        if (value !== -1) {
          if (value.IDayCn === '初一') {
            desc = value.IMonthCn
          } else {
            desc = value.IDayCn
          }
        }
        // console.log(_year, _month, i, value);
      }

      // 如果mode为date
      if (mode === 'date') {
        select = _sameDate(_year, _month, i, selectValue.value as string)
      } else if (mode === 'multi') {
        select = _sameDateInArray(_year, _month, i, selectValue.value as string[]) !== -1
      } else if (mode === 'range') {
        if (_year === startYear.value) {
          if (_month === startMonth.value && _month === endMonth.value) {
            if (i >= startDay.value && i <= endDay.value) {
              select = true
            }
          } else if (_month === startMonth.value) {
            if (i === startDay.value || (i > startDay.value && endDay.value !== 0)) {
              select = true
            }
          } else if (_month === endMonth.value) {
            if (i <= endDay.value) {
              select = true
            }
          }
          // 设置startText endText
          if (startText && _month === startMonth.value && i === startDay.value) {
            desc = startText
          }
          if (endText && _month === endMonth.value && i === endDay.value) {
            desc = endText
          }
        }
      }

      if (_year === maxYear.value && _month === maxMonth.value) {
        if (i > maxDay.value) {
          disabled = true
          select = false
        }
      }

      data.push({
        value: i,
        desc: desc,
        select: select,
        disabled: disabled
      })
    }
    return data
  }

  // 获取对应月份有多少天
  const _getMonthDay = (_year: number, _month: number): number => {
    return new Date(_year, _month, 0).getDate()
  }
  // 获取对应月份的第一天是星期几
  const _getMonthFirstWeekDay = (_year: number, _month: number): number => {
    return new Date(`${_year}/${_month}/01 00:00:00`).getDay()
  }

  // 根据日期设置对应的状态
  const _setDateSelectWithDateValue = (date: string | number, select: boolean, changeMonth: number = 0) => {

    // 查询对应月份对应下标
    if (!changeMonth) changeMonth = month.value
    const monthIndex = calendarData.value.findIndex((item) => item.month === changeMonth)
    if (monthIndex === -1) return

    const index = calendarData.value[monthIndex].data.findIndex((item) => item.value == date)
    // console.log(date, index, select);
    if (index === -1) return
    calendarData.value[monthIndex].data[index].select = select
  }

  // 更新selectValue的值
  const _updateSelectValue = (date: string | number) => {
    const value = `${year.value}/${subNumber(month.value)}/${subNumber(date)}`
    if (mode === 'date') {
      selectValue.value = value
    }
    if (mode === 'multi') {
      const index = _sameDateInArray(year.value, month.value, Number(date), selectValue.value as string[])
      if (index !== -1) {
        (selectValue.value as string[]).splice(index, 1)
      } else {
        (selectValue.value as string[]).push(value)
      }
    }
    if (mode === 'range') {
      selectValue.value = [`${startYear.value}/${subNumber(startMonth.value)}/${subNumber(startDay.value)}`]
      if (endYear.value && endMonth.value && endDay.value) {
        selectValue.value.push(`${endYear.value}/${subNumber(endMonth.value)}/${subNumber(endDay.value)}`)
      }
    }

    // console.log(selectValue.value)
  }

  // 判断日期是否相等
  const _sameDate = (_year: number, _month: number, _day: number, date: string) => {
    if (!date) return false
    return date === `${_year}/${subNumber(_month)}/${subNumber(_day)}`
  }
  // 判断日期是否在对应的数组中
  const _sameDateInArray = (_year: number, _month: number, _day: number, dateArray: string[]) => {
    if (!dateArray || dateArray.length === 0) return -1
    // // 筛选出当前年的数据
    // dateArray = dateArray.filter((item) => {
    //   const date = new Date(item)
    //   return date.getFullYear() === _year
    // })
    const index = dateArray.findIndex((item) => {
      return _sameDate(_year, _month, _day, item)
    })
    return index
  }

  return {
    weekdayZh,
    year,
    month,
    day,
    minYear,
    maxYear,
    startYear,
    startMonth,
    startDay,
    startDate,
    endYear,
    endMonth,
    endDay,
    endDate,
    selectValue,
    calendarData,
    currentShowMonth,
    init,
    setDefaultValue,
    updateCurrentShowMonth,
    updateSelectYear,
    updateSelectValue
  }
}